//
//  LCGroupAddViewController.swift
//  mggz
//
//  Created by QinWei on 2018/1/17.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import ObjectMapper
import Moya
class LCGroupAddViewController: UIViewController {

    @IBOutlet weak var projectName: UILabel!
    
    @IBOutlet weak var tableView: UITableView!
    var membersAddSuccess:((Bool) -> Void)? = nil
    var currentClass: LCClassListModel? {
        willSet {
            self.currentClass = newValue
        }
    }
    var currentProject: LCProjectListModel? {
        willSet {
            self.currentProject = newValue
        }
    }
    
    lazy var addDialog:CustomDialog = {
        var dialog = CustomDialog(frame: CGRect.zero, _title: "提示", _status: "确定要将这些民工加入到该班组中吗？", _submitclick: {
            self.addDialog.dismiss()
            
            guard let accountId = WWUser.sharedInstance.accountId else{
                return
            }
            QWTextWithStatusHud("正在处理中",target:self.view)
            LCAPiMainManager.request(.AddClassMembers(orderId: (self.currentClass?.ID)!, demandBaseWorkIDList: self.membersSelectArray as NSArray, AccountId: accountId)) { (result) in
                QWHudDiss(self.view)
                if case let .success(response) = result {
                    guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                        return
                    }
                    guard (jsonString["State"]) as! String == "OK" else{
                        QWTextonlyHud((jsonString["Err"] as? String ?? ""), target: self.view)
                        return
                    }
                    self.membersAddSuccess!(true)
                    self.navigationController?.popViewController(animated: true)
                }
                
            }
            
        })
        return dialog
    }()
    
    var markArray:NSMutableArray?
    lazy var membersArray : [LCClassMembersModel] = [LCClassMembersModel]()
    lazy var membersSelectArray : [String] = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupNavBar()
        self.projectName.text = self.currentProject?.ProjectName
        self.setupGroupMembersData()
        self.tableView.delegate = self
        self.tableView.dataSource = self
       // self.tableView.separatorStyle = .none
        
        self.tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10)
        self.tableView.separatorInset = UIEdgeInsets.zero
        self.tableView.separatorStyle = .singleLine
        self.tableView.separatorColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.tableView.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        view.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        
        self.tableView.register(UINib.init(nibName: "ClassCheckPersonCell", bundle: nil), forCellReuseIdentifier: "clss")
    }
    fileprivate func setupNavBar(){
        self.navigationItem.title = "成员添加"
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "确定", fontSize: 17, self, #selector(saveAllMembers))
    }
    @objc fileprivate func saveAllMembers(){
        if self.membersSelectArray.count == 0{
            QWTextonlyHud("请先选择民工", target: self.view)
            return
        }
        self.addDialog.show()
        
    }
    fileprivate func setupGroupMembersData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
    LCAPiMainManager.request(.GETClassMembers(MarketSupplyBaseID: (self.currentProject?.MarketSupplyBaseID)!, pageIndex: 1, pageSize: 25, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let resultDic = jsonString["Result"] as? [String: AnyObject] else{
                    return
                }
                guard let itemsArray = resultDic["Items"] as? NSArray else{
                    return
                }
                self.membersArray = Mapper<LCClassMembersModel>().mapArray(JSONObject: itemsArray)!
                self.markArray = NSMutableArray()
                for _ in 0..<self.membersArray.count{
                    self.markArray?.add("0")
                }
                print(self.markArray ?? "空")
                print(self.membersArray)
                print(jsonString)
                self.tableView.reloadData()
            }
        }
    }
}

extension LCGroupAddViewController : UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.membersArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : ClassCheckPersonCell = tableView.dequeueReusableCell(withIdentifier: "clss") as! ClassCheckPersonCell
        cell.setupMembersDataWith(model: self.membersArray[indexPath.row])
        let markStr : String = self.markArray![indexPath.row] as! String
        if markStr == "0"{
            cell.checkView.isHidden = true
        }else if markStr == "1"{
            cell.checkView.isHidden = false
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectModel = self.membersArray[indexPath.row]
        let markStr : String = self.markArray![indexPath.row] as! String
        if markStr == "0"{
        self.markArray?.replaceObject(at: indexPath.row, with: "1")
    self.membersSelectArray.append(selectModel.DemandBaseMigrantWorkerID!)
        }else if markStr == "1"{
            self.markArray?.replaceObject(at: indexPath.row, with: "0")
            for (index,value) in self.membersSelectArray.enumerated(){
                if value == selectModel.DemandBaseMigrantWorkerID{
                    self.membersSelectArray.remove(at: index)
                }
            }
        }
        self.tableView.reloadData()
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 73
    }
}
